<script lang="ts" setup>

import editFormConfig from "./config";
import uploadIcon from "@/assets/icons/upload.png";
import ThingCardSkeleton from "@/components/ThingCardSkeleton/index.vue";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
import { computed, defineAsyncComponent, reactive, ref } from "vue";
import homeIcon from "@/assets/icons/home.png";
import getBASE64 from "@/utils/lib/upload";
import { deleteThing, getAllThing, updateStatusById } from "@/api/thing";

const ThingCard = defineAsyncComponent(
	() => import("@/components/ThingCard/index.vue")
);

const userStore = useUserStore();
const { info } = storeToRefs(userStore);
const head = computed(() => info.value.head);
const money_code = computed(() => info.value.money_code);

const pageData = reactive<Record<string, any>>({
	homeThingList: [],
	isMore: true,
	loading: false,
	listLength: 0 as number,
	pageSize: 3 as number,
	pageNo: 1 as number,
	init: false,
	showModal: false as boolean,
	avatarBASE64: "" as string,
	codeBASE64: "" as string,
	pageEnterTime:0 as number
});

pageData.pageEnterTime = new Date().getTime()

const comEditFormConfig = computed(() => {
	editFormConfig.formItems[0].value = info.value.sex;
	editFormConfig.formItems[1].value = info.value.signature;
	return editFormConfig;
});


// watch(
// 	() => thingList.value,
// 	(value) => {
// 		if (value.length !== 0) {
// 			pageData.homeThingList = value.filter(
// 				(item) => item.user_id === info.value.user_id
// 			);
// 		}
// 	},
// 	{
// 		deep: true,
// 		immediate: true,
// 	}
// );

// 删除个人启事
const deleteThingInfo = async (id: number) => {
	console.log(id);
	pageData.homeThingList = []
	pageData.pageNo = 1
	try {
		await deleteThing({
			id,
		});
		await getHomeThing()
	} catch (error) {
		return Promise.reject(error);
	}
};

const updateStatus = async (value) => {
	try {
		// pageData.homeThingList = []

		pageData.homeThingList = []
	pageData.pageNo = 1
		console.log(value);
		await updateStatusById(value);
		await getHomeThing()
	} catch (error) {
		return Promise.reject(error);
	}
};

const formRef = ref();

// 确定更新用户信息
const onPositiveClick = async () => {
	try {
		const instance: Record<string, any> = formRef?.value?.getFormRef();
		console.log(instance.model);
		const data = {
			head: pageData.avatarBASE64,
			money_code: pageData.codeBASE64,
			user_id: info.value.user_id,
			...instance.model,
		};
		console.log(data);

		await userStore.updateInfo(data);
	} catch (error) {
		return Promise.reject(error);
	}
};

// 取消
const onNegativeClick = () => {
	pageData.showModal = false;
	pageData.avatarBASE64 = head.value;
	pageData.codeBASE64 = money_code.value;
};

const closeModel = () => {
	pageData.showModal = false;
	pageData.avatarBASE64 = head.value;
	pageData.codeBASE64 = money_code.value;
};

// 打开编辑弹窗
const edit = () => {
	pageData.showModal = true;
};
const avatarRef = ref();
const codeRef = ref();

// 触发上传头像方法
const emitUploadAvatar = () => {
	avatarRef.value.click();
};

// 触发上传打赏码方法
const emitUploadCode = () => {
	codeRef.value.click();
};

// 上传头像
const uploadAvatar = async (e) => {
	let file = e.target.files[0];
	if (!file) {
		return;
	}
	let BASE64 = await getBASE64(file);
	pageData.avatarBASE64 = BASE64 as string;
};

// 上传打赏码
const uploadCode = async (e) => {
	let file = e.target.files[0];
	if (!file) {
		return;
	}
	let BASE64 = await getBASE64(file);
	pageData.codeBASE64 = BASE64 as string;
};
/**
 * 获取个人发布的启事
 */
const getHomeThing = async () => {
	try {
		const res = await getAllThing({
			pageNo: pageData.pageNo,
			pageSize: pageData.pageSize,
			user_id: info.value.user_id,
			time:pageData.pageEnterTime
		})
		if (res.data.code === 200) {
			pageData.homeThingList = pageData.homeThingList.concat(res.data.data.data)
			pageData.listLength = res.data.data.dataLength

		}
		return Promise.resolve(res)
	} catch (error) {
		return Promise.reject(error)
	}
}

/**
 * 加载更多
 */
const getMoreThing = async () => {
	try {
		pageData.pageNo += 1
		pageData.loading = true
		await getHomeThing()

		pageData.loading = false

		// window.scrollY = -720

	} catch (error) {
		return Promise.reject(error)
	}
}

// 数据初始化
const init = async () => {
	try {
		await getHomeThing()
		pageData.avatarBASE64 = head.value;
		pageData.codeBASE64 = money_code.value;
		pageData.init = true;
	} catch (error) {
		return Promise.reject(error)
	}
};
init();

</script>

<template>
	<div class="index">
		<div class="things-box">
			<div class="title-box">
				<p class="title">启事</p>
				<p>
					共<span class="count">{{ pageData.listLength }}</span>篇
				</p>
			</div>
			<div class="content">
				<Suspense>
					<template #default>
						<div v-if="!(pageData.homeThingList.length === 0 && pageData.listLength !== 0)">
							<ThingCard @delete="deleteThingInfo" @updateStatus="updateStatus"
								:thingList="pageData.homeThingList" />
							<div class="load-more" @click="getMoreThing" ref="moreRef"
								v-if="pageData.homeThingList.length < pageData.listLength">
								<p v-if="!pageData.loading">加载更多</p>
								<div v-else class="loading">
									<div class="circle-1"></div>
									<div class="circle-2"></div>
								</div>
							</div>
							<div v-else class="no-load">
								<p>已展示全部启事了</p>
							</div>

						</div>
						<div v-else>
							<ThingCardSkeleton />
						</div>
					</template>
					<template #fallback>
						<div>
							<ThingCardSkeleton />
						</div>
					</template>
				</Suspense>
			</div>
		</div>
		<div class="user">
			<div class="avatar">
				<n-image-group>
					<n-image width="150" height="150" :src="head ? head : homeIcon" lazy>
						<template #placeholder>
							<Loading />
						</template>
					</n-image>
				</n-image-group>
			</div>
			<div class="user-box">
				<p>
					<span class="title">用户ID：</span><span>{{ info.user_id }}</span>
				</p>
				<p>
					<span class="title">邮箱：</span><span>{{ info.email }}</span>
				</p>
				<p>
					<span class="title">性别：</span><span>{{ info.sex ? info.sex : "未知" }}</span>
				</p>
				<p>
					<span class="title">上次登录：</span><span>{{ info.login_time }}</span>
				</p>
			</div>
			<div class="signature-box">
				<p>个性签名:</p>
				<p>{{ info.signature ? info.signature : "" }}</p>
			</div>
			<div class="btn-box">
				<n-button type="info" class="edit" v-debounce="edit"> 编辑 </n-button>
			</div>
			<n-modal v-model:show="pageData.showModal" :mask-closable="false" preset="dialog" title="个人信息"
				positive-text="确定" negative-text="取消" style="width: 800px" @positive-click="onPositiveClick"
				@negative-click="onNegativeClick" @after-leave="closeModel">
				<div class="model-box">
					<div class="upload" @click="emitUploadAvatar">
						<img :src="pageData.avatarBASE64" alt="" v-if="pageData.avatarBASE64" class="img" />
						<div class="avatar" v-else>
							<p class="title">点击上传头像</p>
							<img :src="uploadIcon" class="icon" alt="" />
						</div>
						<input type="file" name="" id="" class="file" @change="uploadAvatar" ref="avatarRef" />
					</div>
					<div class="form">
						<Form :config="comEditFormConfig" ref="formRef" />
					</div>
					<div class="upload" @click="emitUploadCode">
						<img :src="pageData.codeBASE64" alt="" v-if="pageData.codeBASE64" class="img" />
						<div class="avatar" v-else>
							<p class="title">点击上传打赏码</p>
							<img :src="uploadIcon" class="icon" alt="" />
						</div>
						<input type="file" name="" id="" class="file" @change="uploadCode" ref="codeRef" />
					</div>
				</div>
			</n-modal>
		</div>
		<div class="code">
			<p class="title">我的打赏码</p>
			<div class="line"></div>
			<div class="img" v-if="money_code">
				<n-image-group>
					<n-image width="170" height="160" :src="money_code ? money_code : ''" lazy>
						<template #placeholder>
							<Loading />
						</template>
					</n-image>
				</n-image-group>
			</div>
		</div>
		<div class="empty"></div>
	</div>
</template>

<style lang="less" scoped>
@import "@/styles/mixin.less";

.index {
	display: grid;
	grid-template-columns: auto 318px;
	grid-template-rows: 400px 160px auto;
	gap: 30px 50px;
	grid-template-areas:
		"things user"
		"things code"
		"things empty";

	.things-box {
		grid-area: things;

		border: 2px solid #ccc;
		box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);

		.without-thing {
			.flex(row, center, center);

			.title {
				font-size: 20px;
				margin-top: 10px;
			}
		}

		.title-box {
			height: 50px;
			padding: 0 20px;
			.flex(row, space-between, center);
			border-bottom: 2px solid #ccc;

			.title {
				color: rgb(3, 180, 170);
				font-weight: bold;
				font-size: 20px;
			}

			.count {
				font-size: 22px;
				color: orange;
			}
		}

		.content {
			.flex(column, flex-start, center);
			// border: 1px solid #aaa;
			padding: 10px 30px;

			.load-more {
				// border: 1px solid #ccc;
				margin: 10px 0;
				height: 40px;
				background-color: rgb(252, 252, 252);
				font-size: 17px;
				// width: 800px;
				.flex(row, center, center);

				&:hover {
					background-color: rgb(245, 246, 248);
					cursor: pointer;
				}

				.loading {
					.flex(row, center, center);

					.circle-1 {
						width: 15px;
						height: 15px;
						border-radius: 50%;
						background-color: blue;
						margin-right: 5px;
						animation: circle1 .6s linear infinite;
					}

					.circle-2 {
						width: 15px;
						height: 15px;
						border-radius: 50%;
						background-color: red;
						animation: circle2 .6s linear infinite;
					}
				}

				@keyframes circle1 {
					50% {
						transform: translateX(20px);
					}
				}

				@keyframes circle2 {
					50% {
						transform: translateX(-20px);
					}
				}
			}

			.no-load {
				margin: 10px 0;
				height: 40px;
				color: #666;
				// width: 800px;
				.flex(row, center, center);
			}

			.without-thing {
				margin-top: 20px;
				text-align: center;
				font-size: 20px;
				color: cornflowerblue;
			}
		}
	}

	.user {
		grid-area: user;
		border: 2px solid #ccc;
		box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);

		// .flex(column,flex-start,center);
		.avatar {
			width: 320px;
			padding: 10px 0;
			border-bottom: 1px solid #ccc;
			.flex(row, center, center);
		}

		.user-box {
			width: 320px;
			.flex(column, center, flex-start);
			padding: 10px 15px;
			border-bottom: 1px solid #ccc;

			.title {
				color: #666;
			}
		}

		.signature-box {
			width: 320px;
			height: 50px;
			padding: 2px 15px;
			border-bottom: 1px solid #ccc;
		}

		.btn-box {
			.flex(row, center, center);
			height: 60px;

			.edit {
				width: 280px;
			}
		}
	}

	.code {
		grid-area: code;
		position: relative;

		.title {
			font-weight: bold;
			font-size: 20px;
			width: 150px;
			// border: 1px solid #ccc;
			background-color: #fff;
			text-align: center;
			position: absolute;
			top: -15px;
			left: 85px;
		}

		.line {
			width: 318px;
			height: 1px;
			background-color: #ccc;
		}

		.img {
			margin-top: 20px;
			// border: 1px solid #ccc;

			width: 318px;

			.flex(row, center, center);
		}
	}

	.empty {
		grid-area: empty;
	}
}

.model-box {
	.flex(row, space-between, center);

	.upload {
		width: 140px;
		height: 150px;
		border: 2px dotted #ccc;
		.flex(column, center, center);

		.img {
			height: 148px;
			width: 135px;
		}

		.avatar {
			.flex(column, center, center);

			.title {
				color: #999;
			}

			.icon {
				margin-top: 10px;
				width: 20px;
				height: 20px;
			}
		}

		&:hover {
			cursor: pointer;
			border: 2px dotted green;
		}

		.file {
			display: none;
		}
	}

	.form {
		flex: 1;
		padding: 0 10px;
	}
}
</style>
